package com.android.djlmapp.activity.login;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.djlmapp.BuildConfig;
import com.android.djlmapp.R;
import com.android.djlmapp.activity.home.HomeActivity;
import com.android.djlmapp.activity.home.web.ForgetPwdActivity;
import com.android.djlmapp.application.MyApplication;
import com.android.djlmapp.base.BaseActivity;
import com.android.djlmapp.dialog.MyUsualyDialog;
import com.android.djlmapp.listener.LocationCallBack;
import com.android.djlmapp.model.home.LocationInfo;
import com.android.djlmapp.model.home.LoginInfo;
import com.android.djlmapp.model.my.ListDataSave;
import com.android.djlmapp.model.my.People;
import com.android.djlmapp.network.ConnectivityType;
import com.android.djlmapp.network.NetWorkStateManager;
import com.android.djlmapp.tools.global.KeyBordUtils;
import com.android.djlmapp.tools.global.ToastUtils;
import com.android.djlmapp.tools.global.UserInfoUtils;
import com.android.djlmapp.tools.login.OnceLocationTools;
import com.android.djlmapp.tools.login.PhoneUtils;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class LoginActivity extends BaseActivity {
    @BindView(R.id.login_ll_waitdialog)
    LinearLayout loginLlWaitdialog;
    @BindView(R.id.login_et_id)
    EditText loginEtId;
    @BindView(R.id.login_et_pwd)
    EditText loginEtPwd;
    @BindView(R.id.login_btn_login)
    Button loginBtnLogin;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    private double latitude;
    private double longitude;
    private String user_name = "";
    private String user_password = "";
    private String phone_os = "";
    private String phone_type = "";
    private String phone_brand = "";
    private String phone_imei = "";
    private String phone_gps = "";
    private String Network = "";
    private String Phone_num = "";
    private String Push_id = "";
    private String version = "";

    private int type = 0; // 第一次登录
    private boolean isLoginTo = false; //防止获取不到位置重复登录
    private NetWorkStateManager manager;
    private Intent mIntent;
    private MyUsualyDialog dialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);

        initView();
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if ("1".equals(mIntent.getStringExtra("cp"))) {
            type = 1; // 第一次登陆
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(loginEtPwd.getWindowToken(), 0);

            user_name = loginEtId.getText().toString().trim();
            user_password = loginEtPwd.getText().toString().trim();

            isLoginTo = false;
            LoginActivityPermissionsDispatcher.openCameraWithCheck(this);
        }
    }

    @Override
    protected void initView() {
        mIntent = getIntent();

        if ("1".equals(mIntent.getStringExtra("cp"))) {
            loginEtId.setText(mIntent.getStringExtra("mUserName"));
            loginEtPwd.setText(mIntent.getStringExtra("mPwd"));

            dialog = new MyUsualyDialog(getActivity(), R.layout.login_waiting);
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    try {
                        if(dialog != null){
                            dialog.dismiss();
                            ToastUtils.showShortToastSafe(getActivity(), "登陆失败,请重试!");
                        }
                    }catch (Exception e){}
                }
            },5000);
        }

        version = BuildConfig.VERSION_NAME;
        UserInfoUtils.getUserInfoUtilsInstance().setVerSion(version); //保存version
    }

    @Override
    protected void initData() {
        tvVersion.setText("V " + version);
        KeyBordUtils.addOnSoftKeyBoardListener(this, new KeyBordUtils.OnSoftKeyBoardListener() {
            @Override
            public void keyBoardShow() {
                //软键盘弹出，隐藏底部控件
                tvVersion.setVisibility(View.GONE);
            }

            @Override
            public void keyBoardHide() {
                //软键盘消失，显示底部控件
                tvVersion.setVisibility(View.VISIBLE);
            }
        });
    }

    @OnClick({R.id.login_btn_seek_pwd, R.id.btn_regist, R.id.login_btn_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login_btn_seek_pwd: // 忘记密码
                Intent intent1 = new Intent(LoginActivity.this, ForgetPwdActivity.class);
                intent1.putExtra("login", "login");
                startActivity(intent1);
                break;
            case R.id.btn_regist: // 注册
                Intent intent = new Intent(LoginActivity.this, RegistActivity.class);
                startActivity(intent);
                break;
            case R.id.login_btn_login:

                type = 1; // 第一次登陆
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(loginEtPwd.getWindowToken(), 0);

                user_name = loginEtId.getText().toString().trim();
                user_password = loginEtPwd.getText().toString().trim();
                if (TextUtils.isEmpty(user_name)) {
                    loginBtnLogin.setEnabled(true);
                    Toast.makeText(LoginActivity.this, "用户名不能为空..", Toast.LENGTH_SHORT).show();
                } else if (TextUtils.isEmpty(user_password)) {
                    loginBtnLogin.setEnabled(true);
                    Toast.makeText(LoginActivity.this, "密码不能为空..", Toast.LENGTH_SHORT).show();
                } else if (TextUtils.isEmpty(user_name) && TextUtils.isEmpty(user_password)) {
                    loginBtnLogin.setEnabled(true);
                    Toast.makeText(LoginActivity.this, "用户名密码不能为空..", Toast.LENGTH_SHORT).show();
                } else if (!TextUtils.isEmpty(user_name) && !TextUtils.isEmpty(user_password)) {
                    loginBtnLogin.setEnabled(false);
                    isLoginTo = false;
                    loginLlWaitdialog.setVisibility(View.VISIBLE);
                    LoginActivityPermissionsDispatcher.openCameraWithCheck(this);
                }
                break;
        }
    }

    private void loginTo() {

        UserInfoUtils.getUserInfoUtilsInstance().setToken("");

        MyApplication.getInstance().getHttpTools().login(Network, Phone_num, Push_id,
                phone_brand, phone_gps, phone_imei, phone_os, phone_type, type + "",
                user_name, user_password, mStringCallback);

    }


    private StringCallback mStringCallback = new StringCallback() {
        @Override
        public void onSuccess(Response<String> response) {
            try {
                String body = response.body();
                Gson gson = new Gson();
                final LoginInfo loginInfo = gson.fromJson(body, LoginInfo.class);
                if (loginInfo != null) {
                    int code = loginInfo.getCode();
                    final String token = loginInfo.getToken();
                    if (code < 1000) {
                        LoginInfo.UserInfo user_info = loginInfo.getUser_info();
                        MyApplication.getInstance().setJPushInit();
                        // 保存用户信息
                        saveUserInfo(token, user_info);

                        Intent intent = new Intent(LoginActivity.this,
                                HomeActivity.class);

                        if ("1".equals(mIntent.getStringExtra("cp")) || "2".equals(mIntent.getStringExtra("cp"))) {
                            // 发送EventBus,关闭宽带首页和地址页
//                            EventBusUtil.sendEvent(new Event<String>(EventCodes.EventMyCode.C));
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
                                    | Intent.FLAG_ACTIVITY_NEW_TASK);
                        }

                        startActivity(intent);
                        finish();
                    } else {
                        ToastUtils.showShortToast(LoginActivity.this, loginInfo.getMsg());
                    }
                }
            } catch (Exception e) {
                Log.e("项目异常", "------Exception------" + e);
                ToastUtils.showShortToast(LoginActivity.this, "数据解析异常");
            }
        }

        @Override
        public void onError(Response<String> response) {
            super.onError(response);
            Log.e("登录结果", "-----onError------" + response.body());
            ToastUtils.showShortToast(LoginActivity.this, "网络或服务器错误");
        }

        @Override
        public void onFinish() {
            super.onFinish();

            if (dialog != null) {
                dialog.dismiss();
                dialog = null;
            }else{
                loginLlWaitdialog.setVisibility(View.INVISIBLE);
                loginBtnLogin.setEnabled(true);
            }
        }
    };

    private void saveUserInfo(String token, LoginInfo.UserInfo user_info) {
        // 登陆成功后存储状态，做为引导页的判断
        UserInfoUtils userInfoUtils = UserInfoUtils.getUserInfoUtilsInstance();

        userInfoUtils.setIsLog(true);// 是否登录
        userInfoUtils.setToken(token); //保存token
//        PrefReadCardTools.setBoolean(LoginActivity.this, "isLog", true); // 是否登录

        // 保存用户登录信息
        userInfoUtils.setPwd(user_password); // 登录密码
        userInfoUtils.setNetWork(Network);
        userInfoUtils.setPhoneNum(Phone_num);
        userInfoUtils.setPushId(Push_id);
        userInfoUtils.setPhoneBrand(phone_brand);
        userInfoUtils.setPhoneGps(phone_gps);
        userInfoUtils.setPhoneImei(phone_imei);
        userInfoUtils.setPhoneOs(phone_os);
        userInfoUtils.setPhoneType(phone_type);

        // 美恰客服需要
        userInfoUtils.setAgent(user_info.getUser_agent());
        userInfoUtils.setFaddress(user_info.getAddress());
        userInfoUtils.setMobile(user_info.getTel());
        userInfoUtils.setUserName(user_info.getName());

        ListDataSave SpdataSave = new ListDataSave(this, "LoginSp");
        List<People> classTests = SpdataSave.getDataList("login");

        //存放登录账号密码
        People user = new People();
        if (classTests.size() == 0) {
            user.setName(user_name);
            user.setPwd(user_password);
            classTests.add(user);
            SpdataSave.setDataList("login", classTests);
        } else {
            List<String> userNames = new ArrayList<>();

            //循环查看是否已保存
            for (int i = 0; i < classTests.size(); i++) {
                userNames.add(classTests.get(i).getName());
                //已有
                if(user_name.equals(classTests.get(i).getName())){
                    //移除
                    classTests.remove(i);

                    user.setName(user_name);
                    user.setPwd(user_password);
                    break;
                }
            }

            boolean contains = userNames.contains(user_name);
            if (contains == false) {
                user.setName(user_name);
                user.setPwd(user_password);
            }

            classTests.add(user);

            //只保留三个账户
            if(classTests.size() > 3){
                for (int i = 0; i < classTests.size() - 3; i++ )
                    classTests.remove(i);
            }

            SpdataSave.setDataList("login", classTests);
        }
    }


    /**
     * 获取手机设备信息
     */
    @SuppressLint("MissingPermission")
    private void getPhoneInfo() {
        //极光推送唯一码
        Push_id = MyApplication.getInstance().getRegistrationId();
        if (Push_id == null) {
            Push_id = "";
        }
        Log.i("推送id", "getPhoneInfo: " + Push_id);
        //手机系统
        phone_os = Build.VERSION.RELEASE;
        //手机型号
        phone_type = Build.MODEL;
        //手机品牌
        phone_brand = Build.MANUFACTURER + "";
        //手机串码
        PhoneUtils phoneUtils = new PhoneUtils(this);
        phone_imei = phoneUtils.getImsi(this) + "";
        //获取手机号码
        TelephonyManager tm = (TelephonyManager) this.getSystemService(this.TELEPHONY_SERVICE);
        Phone_num = tm.getLine1Number() + "";
        manager = NetWorkStateManager.getInstance(getApplicationContext());
        //获取一次网络状态
        ConnectivityType connectedType = manager.getNetWorkState();
        Network = connectedType.getType();
        //实时获取网络状态
//        manager.getRealTimeNetWorkState(new NetWorkStateCallBack() {
//            @Override
//            public void netWorkState(ConnectivityType type) {
//                Network = type.getType();
//                Log.e("项目异常", "------type.getType()------" + type.getType());
//            }
//        });

        getLocationPrem();
    }

    private void getLocationPrem() {

        try {
            OnceLocationTools locationTools = new OnceLocationTools(LoginActivity.this, new LocationCallBack() {
                @Override
                public void successGetLocation(LocationInfo info) {
                    Log.e("坐标获取", info.getLatitude() + "---" + info.getLongitude());
                    latitude = info.getLatitude();
                    longitude = info.getLongitude();
                    phone_gps = latitude + ":" + longitude;
                    loginTo();
                }

                @Override
                public void error(String error) {
                    phone_gps = 0.0 + ":" + 0.0;
                    if (!isLoginTo) {
                        isLoginTo = true;  // 第一次进入就改变状态,防止再次进入,在点击的时候重置状态
                        loginTo();
                    }
                }
            });
            locationTools.startLocation();//开始定位
        } catch (NullPointerException ex) {
            phone_gps = 0.0 + ":" + 0.0;
            loginTo();
        }
    }

    @NeedsPermission({Manifest.permission.READ_SMS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void openCamera() {
        // 获取手机信息
        Log.e("项目异常", "openCamera权限: =================");
        getPhoneInfo();
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        LoginActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({Manifest.permission.READ_SMS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void showCamera(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .setCancelable(false)
                .setMessage("请允许获手机信息,定位权限")
                .show();
    }

    @OnPermissionDenied({Manifest.permission.READ_SMS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void denied() {
        Log.e("权限", "------denied------");
        loginBtnLogin.setEnabled(true);
        loginLlWaitdialog.setVisibility(View.INVISIBLE);
        // 获取手机信息
        ToastUtils.showShortToast(LoginActivity.this, "未获取到定位和手机状态权限,请先打开权限再运行APP");
    }

    @OnNeverAskAgain({Manifest.permission.READ_SMS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void askAgain() {
        Log.e("权限", "------askAgain------");
        loginBtnLogin.setEnabled(true);
        loginLlWaitdialog.setVisibility(View.INVISIBLE);
        // 获取手机信息
        Log.e("项目异常", "askAgain权限: =================");
        ToastUtils.showShortToast(LoginActivity.this, "未获取到定位和手机状态权限,请先打开权限再运行APP");
//        getPhoneInfo();

    }

}
